package cn.iocoder.yudao.module.wecom.service.customer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.wecom.dal.dataobject.acqlinkuser.AcqLinkUserDO;
import cn.iocoder.yudao.module.wecom.dal.dataobject.apiconfig.WeComApiConfigDO;
import cn.iocoder.yudao.module.wecom.dal.dataobject.cusfollowtag.WeCusFollowTagDO;
import cn.iocoder.yudao.module.wecom.dal.dataobject.cusfollowuser.WeCusFollowUserDO;
import cn.iocoder.yudao.module.wecom.dal.dataobject.user.WeUserDO;
import cn.iocoder.yudao.module.wecom.dal.mysql.acqlinkuser.AcqLinkUserMapper;
import cn.iocoder.yudao.module.wecom.dal.mysql.cusfollowtag.WeCusFollowTagMapper;
import cn.iocoder.yudao.module.wecom.dal.mysql.cusfollowuser.WeCusFollowUserMapper;
import cn.iocoder.yudao.module.wecom.dal.mysql.user.WeUserMapper;
import cn.iocoder.yudao.module.wecom.http.WeApi;
import cn.iocoder.yudao.module.wecom.mq.producer.SyncCustomerProducer;
import cn.iocoder.yudao.module.wecom.service.apiconfig.WeComApiConfigService;
import cn.iocoder.yudao.module.wecom.service.customer.dto.CusFollowedUser;
import cn.iocoder.yudao.module.wecom.service.factory.CpServiceFactory;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.contact.ExternalContact;
import me.chanjar.weixin.cp.bean.external.contact.FollowedUser;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.wecom.controller.admin.customer.vo.*;
import cn.iocoder.yudao.module.wecom.dal.dataobject.customer.WeCustomerDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wecom.dal.mysql.customer.WeCustomerMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wecom.enums.ErrorCodeConstants.*;

/**
 * 企微客户 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
@Slf4j
public class WeCustomerServiceImpl implements WeCustomerService {

    @Resource
    private WeCustomerMapper weCustomerMapper;

    @Resource
    private WeUserMapper weUserMapper;

    @Resource
    private WeCusFollowUserMapper weCusFollowUserMapper;

    @Resource
    private WeCusFollowTagMapper weCusFollowTagMapper;

    @Resource
    private AcqLinkUserMapper acqLinkUserMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

//    @Resource
//    private CpServiceFactory cpServiceFactory;

    @Resource
    private SyncCustomerProducer syncCustomerProducer;

    @Resource
    private WeComApiConfigService weComApiConfigService;


    private final static String LOCK_KEY = "QW_SYNC_LOCK:";


    @Override
    public void updateWeCustomer(WeCustomerSaveReqVO updateReqVO) {
        // 更新
        WeCustomerDO updateObj = BeanUtils.toBean(updateReqVO, WeCustomerDO.class);
        weCustomerMapper.updateById(updateObj);
    }

    @Override
    public void deleteWeCustomer(Long id) {
        // 删除
        weCustomerMapper.deleteById(id);
    }

    @Override
    public WeCustomerDO getWeCustomer(Long id) {
        return weCustomerMapper.selectById(id);
    }

    @Override
    public WeCustomerDO getWeCustomer(String weCustomerId) {
        return weCustomerMapper.selectOne(new LambdaQueryWrapperX<WeCustomerDO>()
                .eq(WeCustomerDO::getExternalUserId, weCustomerId), false
        );
    }

    @Override
    public PageResult<WeCustomerDO> getWeCustomerPage(WeCustomerPageReqVO pageReqVO) {
        return weCustomerMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<WeCustomerRespVO> getWeCustomerListByUser(WeCustomerPageReqVO pageReqVO) {
        return weCustomerMapper.selectPage4(pageReqVO);
    }

    @Override
    public Boolean syncWeCustomer() {
        checkLockStatus();
        // 发起一个异步消息通知
        syncCustomerProducer.sendMessage(TenantContextHolder.getTenantId());
        return true;
    }

    @Override
    public List<String> getCustomerIdsByWeUserId(String weUserId) {
        if (StrUtil.isEmpty(weUserId)) {
            return Collections.emptyList();
        }
        List<WeCusFollowUserDO> list = weCusFollowUserMapper.selectList(new LambdaQueryWrapperX<WeCusFollowUserDO>()
                .eq(WeCusFollowUserDO::getQwUserId, weUserId));
        return list.stream().map(WeCusFollowUserDO::getQwCustomerId).collect(Collectors.toList());
    }

    @Override
    public List<String> getCustomerIdsByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            return Collections.emptyList();
        }
        List<WeCustomerDO> list = weCustomerMapper.selectList(new LambdaQueryWrapperX<WeCustomerDO>()
                .eq(WeCustomerDO::getOwnerUserId, userId));
        return list.stream().map(WeCustomerDO::getExternalUserId).collect(Collectors.toList());
    }

    @Override
    public Long getCustomerCountByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            return 0L;
        }
        return weCustomerMapper.selectCount(new LambdaQueryWrapperX<WeCustomerDO>()
                .eq(WeCustomerDO::getOwnerUserId, userId));
    }

    @Override
    public List<WeCustomerDO> getCustomerListByWeCustomerIds(List<String> weCustomerIdList) {
        if (CollUtil.isEmpty(weCustomerIdList)) {
            return Collections.emptyList();
        }

        return weCustomerMapper.selectList(new LambdaQueryWrapperX<WeCustomerDO>()
                .in(WeCustomerDO::getExternalUserId, weCustomerIdList)
        );
    }

    @Override
    public Map<String, WeCustomerDO> getWeCustomerMap(List<String> weCustomerIdList) {
        if (CollUtil.isEmpty(weCustomerIdList)) {
            return Collections.emptyMap();
        }
        List<WeCustomerDO> list = weCustomerMapper.selectList(new LambdaQueryWrapperX<WeCustomerDO>()
                .in(WeCustomerDO::getExternalUserId, weCustomerIdList)
        );
        return CollectionUtils.convertMap(list, WeCustomerDO::getExternalUserId);
    }

    @Override
    public Boolean editCustomerTag(WeCustomerTagUpdateReqVO reqVO) {

        if (CollUtil.isEmpty(reqVO.getAddTag()) && CollUtil.isEmpty(reqVO.getRemoveTag())) {
            throw exception(new ErrorCode(100500, "缺少标签"));
        }

        // 获取企业access_token
        WeComApiConfigDO apiConfig = weComApiConfigService.getWeComApiConfig();
        Map<String, Object> params = new HashMap<>();
        params.put("userid", reqVO.getUserId());
        params.put("external_userid", reqVO.getExternalUserId());
        if (CollUtil.isNotEmpty(reqVO.getAddTag())) {
            params.put("add_tag", reqVO.getAddTag());
        }
        if (CollUtil.isNotEmpty(reqVO.getRemoveTag())) {
            params.put("remove_tag", reqVO.getRemoveTag());
        }
        WeApi weApi = new WeApi(apiConfig.getAccessToken()).body(params);
//        try {
        weApi.markTag();
        if (CollUtil.isNotEmpty(reqVO.getAddTag())) {
            // 插入新的
            reqVO.getAddTag().forEach(item -> {
                weCusFollowTagMapper.insert(new WeCusFollowTagDO()
                        .setWeUserId(reqVO.getUserId())
                        .setWeCustomerId(reqVO.getExternalUserId())
                        .setTagId(item)
                );
            });
        }
        if (CollUtil.isNotEmpty(reqVO.getRemoveTag())) {
            // 删除旧的
            reqVO.getRemoveTag().forEach(item -> {
                weCusFollowTagMapper.delete(new LambdaQueryWrapperX<WeCusFollowTagDO>()
                        .eq(WeCusFollowTagDO::getWeUserId, reqVO.getUserId())
                        .eq(WeCusFollowTagDO::getWeCustomerId, reqVO.getExternalUserId())
                        .eq(WeCusFollowTagDO::getTagId, item)
                );
            });
        }
        return true;
    }

    @Override
    public Boolean bindCustomer(WeCustomerBindReqVO reqVO) {
        if (Objects.equals(1, reqVO.getCustomerStatus())) {
            weCustomerMapper.updateById(new WeCustomerDO().setId(reqVO.getId()).setCustomerStatus(1).setCustomerId(reqVO.getCustomerId()));
        } else {
            weCustomerMapper.updateById(new WeCustomerDO().setId(reqVO.getId()).setCustomerStatus(0).setCustomerId(null));
        }
        return true;
    }

    @Override
    public void addExternalContactHandle(Map<String, Object> allFieldsMap) {
        String AuthCorpId = allFieldsMap.get("AuthCorpId").toString();
        String ExternalUserId = allFieldsMap.get("ExternalUserID").toString();
        String UserID = allFieldsMap.get("UserID").toString();
        WeComApiConfigDO config = weComApiConfigService.getWeComApiConfigByCorpId(AuthCorpId);
        if (Objects.nonNull(config)) {
            TenantUtils.execute(config.getTenantId(), () -> {
                WeUserDO userDO = weUserMapper.selectOne(WeUserDO::getWeUserId, UserID);
                if (Objects.nonNull(userDO)) {
                    initCustomerByExternalContactId(config.getAccessToken(), ExternalUserId, userDO.getSysUserId(), UserID);
                }
            });
        }
    }

    @Override
    public void delExternalExternalContactHandle(Map<String, Object> allFieldsMap) {
        String AuthCorpId = allFieldsMap.get("AuthCorpId").toString();
        String ExternalUserId = allFieldsMap.get("ExternalUserID").toString();
        String UserID = allFieldsMap.get("UserID").toString();
        WeComApiConfigDO config = weComApiConfigService.getWeComApiConfigByCorpId(AuthCorpId);
        if (Objects.nonNull(config)) {
            TenantUtils.execute(config.getTenantId(), () -> {
                WeUserDO user = weUserMapper.selectOne(WeUserDO::getWeUserId, UserID);
                if (Objects.nonNull(user)) {
                    WeCustomerDO customer = getWeCustomer(ExternalUserId);
                    if (Objects.nonNull(customer)) {
                        // 删除客户
                        deleteWeCustomer(customer.getId());
                        // 删除跟进人
                        weCusFollowUserMapper.delete(new LambdaQueryWrapperX<WeCusFollowUserDO>()
                                .eq(WeCusFollowUserDO::getQwCustomerId, ExternalUserId).eq(WeCusFollowUserDO::getQwUserId, UserID));
                        // 删除跟进标签
                        weCusFollowTagMapper.delete(new LambdaQueryWrapperX<WeCusFollowTagDO>().eq(WeCusFollowTagDO::getWeCustomerId, ExternalUserId).eq(WeCusFollowTagDO::getWeUserId, UserID));
                    }
                }

            });
        }
    }

    @Override
    public void delFollowExternalContactHandle(Map<String, Object> allFieldsMap) {
        String AuthCorpId = allFieldsMap.get("AuthCorpId").toString();
        String ExternalUserId = allFieldsMap.get("ExternalUserID").toString();
        String UserID = allFieldsMap.get("UserID").toString();
        WeComApiConfigDO config = weComApiConfigService.getWeComApiConfigByCorpId(AuthCorpId);
        if (Objects.nonNull(config)) {
            TenantUtils.execute(config.getTenantId(), () -> {
                WeUserDO user = weUserMapper.selectOne(WeUserDO::getWeUserId, UserID);
                if (Objects.nonNull(user)) {
                    WeCustomerDO customer = getWeCustomer(ExternalUserId);
                    if (Objects.nonNull(customer)) {
                        // 删除跟进人
                        weCusFollowUserMapper.delete(new LambdaQueryWrapperX<WeCusFollowUserDO>()
                                .eq(WeCusFollowUserDO::getQwCustomerId, ExternalUserId).eq(WeCusFollowUserDO::getQwUserId, UserID));
                        // 删除跟进标签
                        // weCusFollowTagMapper.delete(new LambdaQueryWrapperX<WeCusFollowTagDO>().eq(WeCusFollowTagDO::getWeCustomerId, ExternalUserId).eq(WeCusFollowTagDO::getWeUserId, UserID));
                    }
                }

            });
        }
    }

    /**
     * 校验api调用次数， 10分钟内只能调用一次
     *
     * @author PetePower
     * @since 2024-07-12
     */
    private void checkLockStatus() {
        String lock = stringRedisTemplate.opsForValue().get(LOCK_KEY + TenantContextHolder.getTenantIdStr());
        if (StrUtil.isEmpty(lock)) {
            stringRedisTemplate.opsForValue().set(
                    LOCK_KEY + TenantContextHolder.getTenantIdStr(),
                    "LOCK",
                    30,
                    TimeUnit.MINUTES
            );
        } else {
            throw exception(SYNC_ERROR_API_LIMIT);
        }
    }

    @Override
    public void syncCustomerByMQ() {
        // 获取企业成员
        List<WeUserDO> weUserDOList = weUserMapper.selectList(WeUserDO::getBindStatus, 1);
        if (CollUtil.isEmpty(weUserDOList)) {
            return;
        }
        WeComApiConfigDO apiConfig = weComApiConfigService.getWeComApiConfig();
        for (WeUserDO user : weUserDOList) {
            List<String> externalUserIds = null;
            // GET 客户id列表
            // https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=ACCESS_TOKEN&userid=USERID
            String rest = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=" + apiConfig.getAccessToken() + "&userid=" + user.getWeOpenUserId());
            JSONObject restJson = JSONUtil.parseObj(rest);
            if (ObjectUtil.notEqual(0, restJson.getInt("errcode"))) {
                log.error("同步失败： code: {}, msg: {}", restJson.get("errcode"), restJson.get("errmsg"));
                continue;
            }
            externalUserIds = (List<String>) restJson.getObj("external_userid");
            // TODO: 从数据库里面查找，做减法查询
            List<WeCustomerDO> list = weCustomerMapper.selectList(WeCustomerDO::getOwnerUserId, user.getSysUserId());
            List<String> existCustomerIds = list.stream().map(WeCustomerDO::getExternalUserId).collect(Collectors.toList());
            List<String> newCustomerIds = externalUserIds.stream().filter(item -> !existCustomerIds.contains(item)).collect(Collectors.toList());
            log.info("同步成员客户列表： userid: {} === 企业客户数量 : {}", user.getNickname(), externalUserIds.size());
            log.info("同步成员客户列表： userid: {} === 已有客户数量 : {}", user.getNickname(), existCustomerIds.size());
            log.info("同步成员客户列表： userid: {} === 本次更新客户数量 : {}", user.getNickname(), newCustomerIds.size());
            Integer count = 0;
            if (CollUtil.isNotEmpty(newCustomerIds)) {
                for (String externalUserId : newCustomerIds) {
                    // 客户，init后入库
                    WeCustomerDO customer = initCustomerByExternalContactId(apiConfig.getAccessToken(), externalUserId, user.getSysUserId(), user.getWeUserId());
                    if (Objects.isNull(customer)) {
                        continue;
                    }
                    count++;
                    log.info("同步成员客户列表： userid: {} === 同步进度 : {} / {}", user.getNickname(), count, newCustomerIds.size());

                }
            }
        }
        log.info("获取外部联系FINISH !!!");
    }

    private WeCustomerDO initCustomerByExternalContactId(String accessToken, String externalUserId, Long sysUserId, String weUserId) {
        String rest = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=" + accessToken + "&external_userid=" + externalUserId);
        JSONObject restJson = JSONUtil.parseObj(rest);
        if (ObjectUtil.notEqual(0, restJson.getInt("errcode"))) {
            log.error("客户详情获取失败： code: {}, msg: {}", restJson.get("errcode"), restJson.get("errmsg"));
            return null;
        }
        JSONObject customerBaseInfo = restJson.getJSONObject("external_contact");
        WeCustomerDO customer = null;
        customer = initCustomer(customer, customerBaseInfo);
        customer.setOwnerUserId(sysUserId);
        weCustomerMapper.insertOrUpdate(customer);

        // 2. 解析客户跟进人信息
        JSONArray followUserArray = restJson.getJSONArray("follow_user");

        if (Objects.nonNull(followUserArray)) {
            List<CusFollowedUser> followedUsers = new ArrayList<>();
            for (int i = 0; i < followUserArray.size(); i++) {
                followedUsers.add(JSONUtil.toBean(JSONUtil.parseObj(followUserArray.get(0)), CusFollowedUser.class));
            }

            Long weCustomerId = customer.getId();
            followedUsers.stream().sorted(Comparator.comparing(CusFollowedUser::getCreatetime)).collect(Collectors.toList());
            for (int i = 0; i < followedUsers.size(); i++) {
                CusFollowedUser followedUser = followedUsers.get(i);
                // 插入客户跟进人
                WeCusFollowUserDO cusFollowUser = saveToCusFollowUser(i, followedUser, weCustomerId, externalUserId);

                // ================================ 客户来源活码， 通常为获客链接码， 二维码， 在这里先判断了获客链接来源渠道的处理  ======================
                checkAndSaveCustomerState(cusFollowUser.getState(), weUserId, externalUserId);

                // ================================ 企业客户标签处理 =========================== //
                // -------------------------------- 1. 如果客户详情返回了标签集合， 先删除旧的， 再批量入库新的
                checkAndSaveCustomerTag(followedUser.getTags(), customer.getExternalUserId(), weUserId);

            }
        }
        return customer;
    }

    /**
     * 保存企业客户标签数据
     *
     * @param tags         企微客户列表接口返回的标签列表
     * @param weCustomerId 本地mysql数据库的客户数据id
     * @author PetePower
     * @since 2024-08-27
     */
    private void checkAndSaveCustomerTag(List<CusFollowedUser.FollowedTag> tags, String weCustomerId, String weUserId) {
        if (CollUtil.isEmpty(tags)) {
            return;
        }
        // 先删除， 后批量插入
        weCusFollowTagMapper.delete(new LambdaQueryWrapperX<WeCusFollowTagDO>()
                .eq(WeCusFollowTagDO::getWeCustomerId, weCustomerId)
                .eq(WeCusFollowTagDO::getWeUserId, weUserId));
        tags.forEach(tag -> {
            WeCusFollowTagDO weCusFollowTagDO = BeanUtils.toBean(tag, WeCusFollowTagDO.class);
            weCusFollowTagDO.setWeCustomerId(weCustomerId);
            weCusFollowTagDO.setWeUserId(weUserId);
            weCusFollowTagMapper.insert(weCusFollowTagDO);
//            log.info("客户标签入库： userId : {}, cus: {} , tag: {}", weUserId, weCustomerId, tag.getTagName());
        });
    }

    private void checkAndSaveCustomerState(String state, String weUserId, String externalUserId) {
        if (StrUtil.isEmpty(state)) {
            return;
        }
        // 判断是否为Link 获取链接加入
        if (StrUtil.startWith(state, "LINK_")) {
            String LinkId = StrUtil.subAfter(state, "LINK_", true);
            // 直接入库？
            AcqLinkUserDO acqLinkUserDO = acqLinkUserMapper.selectOne(AcqLinkUserDO::getWeLinkId, LinkId, AcqLinkUserDO::getWeCustomerId, externalUserId);
            if (Objects.isNull(acqLinkUserDO)) {
                acqLinkUserDO = new AcqLinkUserDO();
            }
            acqLinkUserDO.setState(state).setWeUserId(weUserId).setWeCustomerId(externalUserId).setWeLinkId(LinkId);
            acqLinkUserMapper.insertOrUpdate(acqLinkUserDO);
        }
    }

    /**
     * 保存客户跟进人
     *
     * @param i              跟进人数组游标， 0表示第一个跟进人，首要跟进人
     * @param followedUser   接口返回的跟进人json对象
     * @param weCustomerId   数据库本地的客户数据id
     * @param externalUserId 企微的客户外部联系人id，字符串类型
     * @return 客户跟进人对象
     * @author PetePower
     * @since 2024-08-27
     */
    private WeCusFollowUserDO saveToCusFollowUser(int i, CusFollowedUser followedUser, Long weCustomerId, String externalUserId) {

        // 从本地获取followUser
        WeCusFollowUserDO cusFollowUser = weCusFollowUserMapper.selectOne(WeCusFollowUserDO::getQwCustomerId, externalUserId, WeCusFollowUserDO::getQwUserId, followedUser.getUserid());
        if (Objects.isNull(cusFollowUser)) {
            // 跟进人本地不存在 -> 新的记录， 全部入库 ->
            cusFollowUser = new WeCusFollowUserDO();
            if (i == 0) {
                cusFollowUser.setLevel(0);
            }
            cusFollowUser.setCreateTime(LocalDateTimeUtil.of(followedUser.getCreatetime() * 1000));
        }
        cusFollowUser.setCustomerId(weCustomerId);
        cusFollowUser.setQwCustomerId(externalUserId);
        cusFollowUser.setQwUserId(followedUser.getUserid());
        cusFollowUser.setAddWay(followedUser.getAddWay());
        cusFollowUser.setOperUserId(followedUser.getOperUserid());
        cusFollowUser.setRemark(followedUser.getRemark());
        cusFollowUser.setDescription(followedUser.getDescription());
        cusFollowUser.setRemarkMobiles(followedUser.getRemarkMobiles());
        cusFollowUser.setRemarkCorpName(followedUser.getRemarkCorpName());

        if (Objects.nonNull(followedUser.getWechatChannels())) {
            cusFollowUser.setWechatChannelSource(String.valueOf(followedUser.getWechatChannels().getSource()));
            cusFollowUser.setWechatChannelNickname(followedUser.getWechatChannels().getNickname());
        }
        cusFollowUser.setState(followedUser.getState());
        weCusFollowUserMapper.insertOrUpdate(cusFollowUser);
        return cusFollowUser;
    }

    private WeCustomerDO initCustomer(WeCustomerDO customer, JSONObject externalContact) {
        if (Objects.isNull(customer)) {
            // 1. 新的客户，init后入库
            customer = new WeCustomerDO();
        }
        // 外部联系人id
        customer.setExternalUserId(externalContact.getStr("external_userid"));
        customer.setName(externalContact.getStr("name"));
        customer.setAvatar(externalContact.getStr("avatar"));
        customer.setCorpName(externalContact.getStr("corp_name"));
        customer.setCorpFullName(externalContact.getStr("corp_full_name"));
        customer.setPositionName(externalContact.getStr("position"));
        // 客户类型： 1-微信用户； 2-企业微信用户
        customer.setType(externalContact.getInt("type"));
        customer.setGender(externalContact.getInt("gender"));
        customer.setUnionId(externalContact.getStr("unionid"));
        return customer;
    }
}